package com.lhkj.ct.meta.modules.report.word;

import com.aspose.words.Bookmark;
import com.aspose.words.BookmarkCollection;
import com.aspose.words.Document;
import com.aspose.words.DocumentBuilder;
import com.lhkj.ct.base.exception.SystemException;
import com.lhkj.ct.base.utils.file.FileUtils;
import com.lhkj.ct.base.utils.file.word.AsposeWordsUtil;
import com.lhkj.ct.meta.modules.report.AbstractReportHandle;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Optional;

/**
 * <p>
 *     心理咨询报告处理类
 * </p>
 */
public class CounselingHandle extends AbstractReportHandle<Map<String, Object>, Document> {

    public CounselingHandle() {

    }

    @Override
    public Document generateReport(Map<String, Object> data) {
        // step 读取word模板,此处使用书签模式，在word中插入->书签添加书签
        try (InputStream is = FileUtils.readResourceFile("report\\心理咨询报告模板.docx")){
            if (!AsposeWordsUtil.getLicense()) {
                throw new SystemException("PDF生成授权凭证无效");
            }
            Document document = new Document(is);
            DocumentBuilder builder = new DocumentBuilder(document);
            BookmarkCollection bookmarks = document.getRange().getBookmarks();
            // tips 此处可考虑使用策略模式+自定义策略进行设计
            for (Bookmark bookmark : bookmarks) {
                String name = bookmark.getName();
                builder.moveToBookmark(name);
                if (StringUtils.equals("evaluationContent", name)) {
                    builder.insertHtml(Optional.ofNullable(data.get(bookmark.getName())).orElse(StringUtils.EMPTY).toString());
                    continue;
                }
                builder.write(Optional.ofNullable(data.get(bookmark.getName())).orElse(StringUtils.EMPTY).toString());
            }
            return document;
            //3 图片指定插件
//            ConfigureBuilder builder = Configure.builder();
//            builder.buildGramer("${", "}");
//            Configure config = builder.build();
//
//            // html渲染插件
//            HtmlRenderPolicy htmlRenderPolicy = new HtmlRenderPolicy();
//            config.customPolicy("evaluationContent", htmlRenderPolicy);
//            // 读取模板文件，并渲染数据
//            XWPFTemplate template  = XWPFTemplate.compile(is, config).render(data);
            // 写入文件
//            return template.getXWPFDocument();
        } catch (IOException e) {
            throw new SystemException("模板加载失败");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
